<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <link rel="stylesheet" href="../../lib/jq-module/zyupload/zyupload-1.0.0.min.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }

        .width100 {
            width: 100px;
        }

    </style>
</head>
<body>
<div class="layui-form layuimini-form" lay-filter="role-form">

    <div class="layui-form-item">
        <label class="layui-form-label required">创建时间</label>
        <div class="layui-input-block">
            <input type="text" name="createTime" readonly value="" class="layui-input" readonly>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">平台ID</label>
        <div class="layui-input-block">
            <input type="text" name="userId" readonly value="" class="layui-input" readonly>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">平台昵称</label>
        <div class="layui-input-block">
            <input type="text" name="userName" readonly value="" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">员工姓名</label>
        <div class="layui-input-block">
            <input type="text" name="realName" placeholder="请填写员工姓名" value="" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">快捷支付</label>
        <div class="layui-input-block">
            <input type="checkbox" name="quickPay" id="quickPaySwitch" lay-filter="quickPaySwitch" lay-skin="switch"
                   lay-text="ON|OFF">
        </div>
    </div>

    <div class="layui-form-item" style="padding-left: 20px;">
        <div class="layui-inline">
            <label class="layui-form-label width100">重置后台密码</label>
            <div class="layui-input-inline">
                <input type="text" name="newPassword" lay-verify="newPassword" placeholder="请重置登录密码" value=""
                       class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label required">登录权限</label>
            <div class="layui-input-inline">
                <input type="checkbox" name="status" id="statusSwitch" lay-filter="statusSwitch" lay-skin="switch"
                       lay-text="ON|OFF">
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">员工身份</label>
        <div class="layui-input-inline">
            <select name="identity" lay-filter="identity">
                <option value="">不限</option>
                <option value="0">管理员</option>
                <option value="1">推广员</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item layui-form-text" id="admin" style="display: none">
        <label class="layui-form-label">管理权限</label>
        <div class="layui-input-block">
            <div id="menuIds"></div>
            <input type="text" name="menuIds" value="" hidden>
        </div>
    </div>

    <!-- 推广员 -->
    <div class="layui-form-item" id="promoter" style="padding-left: 40px;display: none">
        <div class="layui-inline">
            <div class="layui-inline">
                <label class="layui-form-label">提现限制</label>
                <div class="layui-input-inline">
                    <input type="checkbox" name="cashOutLimit" id="cashOutLimitSwitch" lay-filter="cashOutLimitSwitch"
                           lay-skin="switch" lay-text="ON|OFF">
                </div>
            </div>
            <div class="layui-inline" id="coins">
                <label class="layui-form-label width100">帐户余额（元）</label>
                <div class="layui-input-inline">
                    <input type="text" name="accountBalance" value="" class="layui-input">
                </div>
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">保存</button>
        </div>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script>

    let userId = '';
    let action = '';
    let tree;
    let table;
    let initCashOutLimit = "";// 是否开启提现限制初始值
    window.onload = function () {
        userId = GetQueryString("userId");
        action = GetQueryString("action");
        if (isNotNull(userId) && isNotNull(action)) {
            init(userId, action);
        } else {
            const iframeIndex = parent.layer.getFrameIndex(window.name);
            parent.layer.close(iframeIndex);
        }
    }

    layui.use(['form'], function () {
        var form = layui.form
            , layer = layui.layer
        $ = layui.$;
        table = layui.table
            , tree = layui.tree;

        // 监听员工身份下拉选择
        form.on('select(identity)', function (dataObj) {
            let identity = $('select[name="identity"]').find("option:selected").val();
            if (identity === '0') {//管理员
                getManagePermissions(userId);// 获取管理权限
                $("#admin").show();
                $("#promoter").hide();
            } else if (identity === '1') {//推广员
                if ($("#cashOutLimitSwitch").is(':checked')) {
                    getAccountBalance(userId);// 开启提醒限制，则获取用户的帐户余额
                }
                $("#admin").hide();
                $("#promoter").show();
            } else {// 不限
                $("#admin").hide();
                $("#promoter").hide();
            }

        });

        // 监听多选框点击事件---提现限制
        form.on('switch(cashOutLimitSwitch)', function (data) {
            if (data.elem.checked) {// 打开
                $("#coins").show();
                getAccountBalance(userId);// 获取账户余额
            } else {// 关闭
                $("#coins").hide();
                if (initCashOutLimit == '1') {
                    layer.msg("若关闭【提现限制】，则会清空账户余额，请谨慎操作！");
                }
            }
        });

        // 校验表格字段
        form.verify({
            newPassword: function (value, item) { //value：表单的值、item：表单的DOM对象
                if (isNotNull(value)) {
                    if (value.length < 6) {
                        return '密码长度不得少于6位';
                    }
                }
            }
        });

        // 监听提交
        form.on('submit(saveBtn)', function (data) {

            // 快捷支付。0:关闭；1:开启
            if ($("#quickPaySwitch").is(':checked')) {
                data.field.quickPay = '1';
            } else {
                data.field.quickPay = '0';
            }

            // 登录权限。0:开启；1:关闭
            if ($("#statusSwitch").is(':checked')) {
                data.field.status = '0';
            } else {
                data.field.status = '1';
            }

            // 提现限制。0:关闭；1:开启
            if ($("#cashOutLimitSwitch").is(':checked')) {
                data.field.cashOutLimit = '1';
            } else {
                data.field.cashOutLimit = '0';
            }

            // 员工身份
            data.field.identity = $('select[name="identity"]').find("option:selected").val();
            if (data.field.identity == 1) {// 推广员
                // 如果原来是推广员的身份，修改后还是推广员，在需要判断是否需要清空账户余额；
                // 若原来是推广员，修改成其他身份了，则不需要考虑清空账户余额
                // 如果初始值=1(开启提现限制)，修改后=0(关闭提现限制)，则需要清空账户余额
                if (initCashOutLimit == '1' && data.field.cashOutLimit == '0') {
                    data.field.emptyWallet = '1';// 是否清空钱包，0:否；1:是；
                }
            }

            console.log(data);

            var index = layer.alert('确定提交修改吗？', {
                title: '提示'
            }, function () {
                let myMsg = layer.msg("正在提交...", {
                    icon: 16,
                    time: -1
                })
                $.ajax({
                    type: "post",
                    url: '/user/edit/staff',
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json; charset=UTF-8',
                    success: function (req) {
                        if (req.code != 200) {
                            layer.msg(req.msg);
                        } else {
                            layer.msg("保存成功");
                            layer.close(index);
                            // 关闭弹出层
                            setTimeout(function () {
                                layer.close(myMsg);//手动关闭
                                let iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                            }, 1500);
                        }
                    },
                    error: function (e) {
                        layer.msg("保存失败");
                        layer.close(myMsg);//手动关闭
                    }
                })
            });
            return false;
        });
    });

    /**
     * 初始化数据
     */
    function init(userId, action) {

        // 直接查询meily_user
        let url = '/user/info/' + userId;

        if (action == "add") {
            // 新增，需要查询系统用户信息
            url = '/user/info/staff/' + userId;
        }

        $.ajax({
            type: "get",
            url: url,
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (req) {
                if (req.userInfo == null || !isNotNull(req.userInfo.userId)) {
                    layer.msg(req.msg);
                    setTimeout(function () {
                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(iframeIndex);
                    }, 500)
                }

                // 创建时间
                let _createTime = req.userInfo.createTime;
                if (!isNotNull(_createTime)) {
                    _createTime = _getTimes();// 当前时间
                }

                // 记录初始值
                initCashOutLimit = req.userInfo.cashOutLimit;

                layui.use(['form'], function () {
                    const form = layui.form
                        , $ = layui.$;
                    form.val('role-form', {
                        "createTime": _createTime,
                        "userId": req.userInfo.userId,
                        "userName": req.userInfo.userName,
                        "realName": req.userInfo.realName,
                        "quickPay": Number(req.userInfo.quickPay),
                        "cashOutLimit": Number(req.userInfo.cashOutLimit),
                        "status": req.userInfo.status,
                        "identity": req.userInfo.identity
                    });

                    if (req.userInfo.identity === '0') {
                        getManagePermissions(userId);// 获取管理权限
                        $("#admin").show();
                        $("#promoter").hide();
                    } else if (req.userInfo.identity === '1') {
                        if ($("#cashOutLimitSwitch").is(':checked')) {
                            getAccountBalance(userId);// 开启提醒限制，则获取用户的帐户余额
                        }
                        $("#admin").hide();
                        $("#promoter").show();
                    } else {
                        $("#admin").hide();
                        $("#promoter").hide();
                    }
                    if (req.userInfo.status === '1') {
                        $('#statusSwitch').prop("checked", false);
                        form.render();
                    }
                })
            },
            error: function (e) {
                layer.msg("数据有误");
            }
        });
    }

    /**
     * 获取管理权限(菜单树列表)
     */
    function getManagePermissions(userId) {
        let data;
        $.ajax({
            type: "get",
            url: '/menu/roleMenuTreeDataByUserId/' + userId,
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            async: false,
            success: function (req) {
                data = req.data;
            },
            error: function (e) {
                alert("出错啦！")
            }
        });

        // 初始化树形菜单
        // localStorage.setItem('checkChild',"false");//初始化去掉全选功能
        tree.render({
            elem: '#menuIds'  //绑定元素
            , id: 'menuTreeId'
            // ,showCheckbox: true
            , checkChild: false
            , data: data
        });
        // localStorage.setItem('checkChild',"true");//初始化页面完成后恢复全选功能
    }

    /**
     * 获取帐户余额
     */
    function getAccountBalance(userId) {
        let data;
        let obj = {userId: userId};
        $.ajax({
            type: "post",
            url: '/user/getCoins/staff',
            data: JSON.stringify(obj),
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            async: false,
            success: function (req) {
                data = req.msg;
            },
            error: function (e) {
                alert("出错啦！")
            }
        });
        $('input[name="accountBalance"]').val(data);
    }
</script>
</body>
</html>
